package yunjiao.javatutorials.guava.concurrent.log;

import yunjiao.javatutorials.guava.concurrent.ForwardingLock;

import java.util.concurrent.locks.Lock;

/**
 * 添加日志功能的锁
 *
 * @author yangyunjiao
 */
public class LoggingLock extends ForwardingLock {
    private final Lock delegate;
    private final String name;

    public LoggingLock(Lock delegate, String name) {
        this.delegate = delegate;
        this.name = name;
    }

    @Override
    protected Lock delegate() {
        return delegate;
    }

    @Override
    public void lock() {
        System.out.println("[" + name + "] Attempting to acquire lock...");
        long startTime = System.currentTimeMillis();
        super.lock();
        long endTime = System.currentTimeMillis();
        System.out.println("[" + name + "] Lock acquired after " + (endTime - startTime) + "ms");
    }

    @Override
    public void unlock() {
        System.out.println("[" + name + "] Releasing lock");
        super.unlock();
    }

    @Override
    public boolean tryLock() {
        System.out.println("[" + name + "] Attempting to tryLock...");
        boolean result = super.tryLock();
        System.out.println("[" + name + "] tryLock result: " + result);
        return result;
    }
}
